package com.wenyu.wenyuyuedu.activity.personage;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentValues;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.tbruyelle.rxpermissions.RxPermissions;
import com.wenyu.wenyuyuedu.R;
import com.wenyu.wenyuyuedu.activity.LoginActivity;
import com.wenyu.wenyuyuedu.bean.personage.AlertHeadBean;
import com.wenyu.wenyuyuedu.bean.personage.ShowHeadNicknameBean;
import com.wenyu.wenyuyuedu.global.ApiWrapper;
import com.wenyu.wenyuyuedu.server.personage.AlertHeadServer;
import com.wenyu.wenyuyuedu.server.personage.ShowHeadNicknameServer;
import com.wenyu.wenyuyuedu.utils.AbSharedUtil;
import com.wenyu.wenyuyuedu.utils.ImageUtils;
import com.wenyu.wenyuyuedu.utils.MyToast;
import com.wenyu.wenyuyuedu.utils.SharedConstants;
import com.wenyu.wenyuyuedu.utils.StatusBarUtil;
import com.wenyu.wenyuyuedu.view.CircleImageView;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.ButterKnife;
import butterknife.InjectView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import rx.functions.Action1;

/*
* 修改昵称和头像
* */
public class SelectHeadActivity extends AppCompatActivity implements View.OnClickListener {

    @InjectView(R.id.iv_left)
    ImageView ivLeft;
    @InjectView(R.id.rl_alert_head)
    RelativeLayout rlAlertHead;
    @InjectView(R.id.rl_alert_name)
    RelativeLayout rlAlertName;
    @InjectView(R.id.ci_personage_head)
    CircleImageView ciPersonageHead;
    @InjectView(R.id.tv_select_name)
    TextView tvSelectName;
    private Intent intent;
    Dialog dialog;
    private Uri imageUri;
    /* 请求码 */
    private static final int IMAGE_REQUEST_CODE = 0;
    private static final int CAMERA_REQUEST_CODE = 1;
    private static final int RESULT_REQUEST_CODE = 2;
    private String newFilePath;
    private String strpathing;
    private Boolean tag_photo;
    private String bitmapToString;
    private static final String IMGURL = Environment
            .getExternalStorageDirectory() + "/Android/data/com.hang.dialog/";
    /* 照相机缓存头像名称 */
    private static final String IMAGE_FILE_NAME_TEMP = "temp_faceImage.jpg";
    /* 头像名称 */
    private static final String IMAGE_FILE_NAME = "faceImage.jpg";
    private File file;
    private RxPermissions rxPermissions;
    private Activity activity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_head);
        StatusBarUtil.setStatusBar(SelectHeadActivity.this, R.color.white);
        ButterKnife.inject(this);
        activity = SelectHeadActivity.this;
        rxPermissions = new RxPermissions(this);
        rxPermissions.setLogging(true);
        initView();
    }

    @Override
    protected void onStart() {
        super.onStart();
        requestData();
    }

    /*展示昵称和头像*/
    private void requestData() {
        String token = AbSharedUtil.getString(SelectHeadActivity.this, SharedConstants.USER_TOKEN);
        ShowHeadNicknameServer showHeadNicknameServer = ApiWrapper.getInstance().create(ShowHeadNicknameServer.class);
        Call<ShowHeadNicknameBean> headNickname = showHeadNicknameServer.getHeadNickname(token);
        headNickname.enqueue(new Callback<ShowHeadNicknameBean>() {
            @Override
            public void onResponse(Call<ShowHeadNicknameBean> call, Response<ShowHeadNicknameBean> response) {
                ShowHeadNicknameBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        tvSelectName.setText(body.getInfo().getNickname());
                        Glide.with(SelectHeadActivity.this)
                                .load(body.getInfo().getIcon())
                                .error(R.drawable.login_logo)
                                .into(ciPersonageHead);
                        AbSharedUtil.putString(SelectHeadActivity.this, SharedConstants.USER_NICKNAME, tvSelectName.getText().toString());
                    } else if (code == 0) {
                        showLoginDoalog();
                    } else if (code == 5000) {
                        MyToast.showToast(SelectHeadActivity.this, "系统繁忙", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<ShowHeadNicknameBean> call, Throwable t) {
                MyToast.showToast(SelectHeadActivity.this, "系统繁忙，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }

    /*
    * 初始化控件的点击事件
    * */
    private void initView() {
        intent = new Intent();
        ivLeft.setOnClickListener(this);
        rlAlertHead.setOnClickListener(this);
        rlAlertName.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.iv_left:
                finish();
                break;
            //修改头像
            case R.id.rl_alert_head:
                showDialog();
                break;
            //修改昵称
            case R.id.rl_alert_name:
                intent.setClass(SelectHeadActivity.this, AlertNameActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void showDialog() {
        View view = getLayoutInflater().inflate(R.layout.photo_choose_dialog,
                null);
        dialog = new Dialog(this, R.style.transparentFrameWindowStyle);
        dialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
        Window window = dialog.getWindow();
        // 设置显示动画
        window.setWindowAnimations(R.style.main_menu_animstyle);
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.x = 0;
        wl.y = getWindowManager().getDefaultDisplay().getHeight();
        // 以下这两句是为了保证按钮可以水平满屏
        wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
        wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;

        // 设置显示位置
        dialog.onWindowAttributesChanged(wl);
        // 设置点击外围解散
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    //在布局写好监听属性
    public void on_click(View v) {
        switch (v.getId()) {
            //打开相机
            case R.id.openCamera:
                // openCamera();
                rxPermissions.request(Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE)
                        .subscribe(new Action1<Boolean>() {
                            @Override
                            public void call(Boolean aBoolean) {
                                Boolean aBoolean1 = aBoolean;
                                if (aBoolean) {
                                    //打开相机
                                    openCamera();
                                } else {
                                    /*获取权限的dialog*/
                                    gianPermision();
                                }
                            }
                        });

                break;
            /*打开图库*/
            case R.id.openPhones:
                openPhones();
                break;
            case R.id.cancel:
                dialog.cancel();
                break;
            default:
                break;
        }
    }

    android.app.AlertDialog adPermision;
    private TextView quxiaoPermision;
    private TextView quedingPermision;


    /*获取权限的dialog*/
    private void gianPermision() {
        adPermision = new android.app.AlertDialog.Builder(activity).create();
        adPermision.show();
        Window window = adPermision.getWindow();
        window.setContentView(R.layout.dailog_permissions);
        quxiaoPermision = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        quedingPermision = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiaoPermision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                adPermision.dismiss();
            }
        });
        quedingPermision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
                if (Build.VERSION.SDK_INT >= 9) {
                    Uri packageURI = Uri.parse("package:" + activity.getPackageName());
                    intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                    activity.startActivity(intent);
                } else if (Build.VERSION.SDK_INT <= 8) {
                    intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                    intent.putExtra("com.android.settings.ApplicationPkgName", activity.getPackageName());
                    activity.startActivity(intent);
                }
                adPermision.dismiss();
            }
        });
    }

    // 打开相册
    private void openPhones() {
        Intent intent_gallery = new Intent(
                Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent_gallery
                .setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
        startActivityForResult(intent_gallery,
                IMAGE_REQUEST_CODE);


    }

    // 打开照相机
    private void openCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(activity.getPackageManager()) != null) {
            File file = new File(Environment.getExternalStorageDirectory(), "image.jpg");
            if (file != null) {
                 /*获取当前系统的android版本号*/
                int currentapiVersion = android.os.Build.VERSION.SDK_INT;
                Log.e("currentapiVersion", "currentapiVersion====>" + currentapiVersion);
                if (currentapiVersion < 24) {
                    imageUri = Uri.fromFile(file);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, CAMERA_REQUEST_CODE);
                } else {
                    ContentValues contentValues = new ContentValues(1);
                    contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpg");
                    imageUri = this.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                    startActivityForResult(intent, CAMERA_REQUEST_CODE);
                }
            } else {
                Toast.makeText(activity, "文件读取错误", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(activity, "文件读取错误", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 2);
    }

    private void saveCroppedImage(Bitmap bmp) {
        File file = new File("/sdcard/myFolder");
        if (!file.exists())
            file.mkdir();

        file = new File("/sdcard/temp.jpg".trim());
        String fileName = file.getName();
        String mName = fileName.substring(0, fileName.lastIndexOf("."));
        String sName = fileName.substring(fileName.lastIndexOf("."));
        //sdcard/myFolder/temp_cropped.jpg
        newFilePath = "/sdcard/myFolder" + "/" + mName + "_cropped" + sName;
        file = new File(newFilePath);
        Log.e("-nnnnn", newFilePath);
        try {
            file.createNewFile();
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 50, fos);
            fos.flush();
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    //把bitmap转换成字符串
    public static String bitmapToString(Bitmap bitmap) {
        String string = null;
        ByteArrayOutputStream btString = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, btString);
        byte[] bytes = btString.toByteArray();
        string = Base64.encodeToString(bytes, Base64.DEFAULT);
        return string;
    }

    private void initFileName() {
        file = new File("/sdcard/myFolder");
        if (!file.exists())
            file.mkdir();

        file = new File("/sdcard/temp.jpg".trim());
        String fileName = file.getName();
        String mName = fileName.substring(0, fileName.lastIndexOf("."));
        String sName = fileName.substring(fileName.lastIndexOf("."));

        // /sdcard/myFolder/temp_cropped.jpg
        newFilePath = "/sdcard/myFolder" + "/" + mName + "_cropped" + sName;
        file = new File(newFilePath);
        System.out.println("path---" + file.getAbsolutePath());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //获取图片
        // 结果码不等于取消时候
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case IMAGE_REQUEST_CODE:// 打开相册返回
                    startPhotoZoom(data.getData());
                    Uri selectedImage = data.getData();
                    String schene = selectedImage.getScheme();
                    if ("file".equals(schene)) {
                        strpathing = selectedImage.getPath();
                        Bitmap bitmap = ImageUtils.getimage(strpathing);
                        saveCroppedImage(bitmap);
                    }
                    tag_photo = true;
                    break;
                case CAMERA_REQUEST_CODE:// 打开相机返回
                    startPhotoZoom(imageUri);
                    tag_photo = true;
                    break;
                case RESULT_REQUEST_CODE:// 裁剪完成,删除照相机缓存的图片
                    final File tempFile = new File(IMGURL + IMAGE_FILE_NAME_TEMP);
                    if (tempFile.exists()) {
                        new Thread() {
                            public void run() {
                                tempFile.delete();
                            }

                            ;
                        }.start();
                    }
                    // 保存截取后的图片
                    tag_photo = true;
                    if (data != null) {
                        Bundle extras = data.getExtras();
                        if (extras != null) {
                            Bitmap photo = extras.getParcelable("data");
                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
                            photo.compress(Bitmap.CompressFormat.JPEG, 100, baos);
                            ciPersonageHead.setImageBitmap(photo);
                            //点击图库选择的保存的图片
                            bitmapToString = bitmapToString(photo);
                            AlertHead(bitmapToString);
                        }
                    }
                    dialog.cancel();//关闭dialog
                    break;
            }
        }

    }

    /*修改头像*/
    private void AlertHead(String bitmapToString) {
        String token = AbSharedUtil.getString(SelectHeadActivity.this, SharedConstants.USER_TOKEN);
        AlertHeadServer uploadImageServer = ApiWrapper.getInstance().create(AlertHeadServer.class);
        Call<AlertHeadBean> image = uploadImageServer.getHead(token, bitmapToString);
        image.enqueue(new Callback<AlertHeadBean>() {
            @Override
            public void onResponse(Call<AlertHeadBean> call, Response<AlertHeadBean> response) {
                AlertHeadBean body = response.body();
                if (body != null) {
                    int code = body.getCode();
                    if (code == 1) {
                        String info = body.getInfo();
                        Glide.with(SelectHeadActivity.this)
                                .load(info)
                                .error(R.drawable.login_logo)
                                .into(ciPersonageHead);
                        MyToast.showToast(SelectHeadActivity.this, "保存成功", Toast.LENGTH_SHORT);
                    } else if (code == 0) {
                        showLoginDoalog();
                    } else if (code == 5101) {
                        MyToast.showToast(SelectHeadActivity.this, "获取图片失败", Toast.LENGTH_SHORT);
                    } else if (code == 5100) {
                        MyToast.showToast(SelectHeadActivity.this, "系统繁忙，请您稍后再试！", Toast.LENGTH_SHORT);
                    }
                }
            }

            @Override
            public void onFailure(Call<AlertHeadBean> call, Throwable t) {
                MyToast.showToast(SelectHeadActivity.this, "系统繁忙，请稍后重试！", Toast.LENGTH_SHORT);
            }
        });
    }

    android.app.AlertDialog ad;
    private TextView quxiao;
    private TextView queding;

    /*显示登陆的dialog*/
    private void showLoginDoalog() {

        ad = new android.app.AlertDialog.Builder(activity).create();
        ad.show();
        Window window = ad.getWindow();
        window.setContentView(R.layout.dailog_login);
        quxiao = (TextView) window.findViewById(R.id.dialog_login_quxiao);
        queding = (TextView) window.findViewById(R.id.dialog_login_queding);
        quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ad.dismiss();
            }
        });
        queding.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.setClass(SelectHeadActivity.this, LoginActivity.class);
                startActivity(intent);
                finish();
                ad.dismiss();
            }
        });
    }
}
